package com.qidian.study.service.impl;

import com.qidian.study.dao.UserBaseDAO;
import com.qidian.study.dao.impl.UserBaseDAOImpl;
import com.qidian.study.pojo.UserBase;
import com.qidian.study.service.UserBaseService;
import com.qidian.study.util.JsonTools;
import com.qidian.study.util.RedisUtil;
import com.qidian.study.util.pojo.VideoResponse;

import java.util.Random;
import java.util.UUID;

/**
 * @author 戴着假发的程序员
 * @company 起点编程
 */
public class UserBaseServiceImpl implements UserBaseService {
    private UserBaseDAO userBaseDAO = new UserBaseDAOImpl();
    private RedisUtil redisUtil = new RedisUtil();
    @Override
    public VideoResponse login(String username, String userpass) {
        UserBase userBase = userBaseDAO.queryByName(username);
        if(userBase == null){
            return  VideoResponse.error();
        }
        if(userBase.getUserpass().equals(userpass)){
            // 登陆成功
            // 将用户信息放入redis
            // 生成一个token
            String token = UUID.randomUUID().toString().replace("-","")+(new Random().nextInt(900)+100);
            userBase.setUserpass("");
            String userJson = JsonTools.object2json(userBase);
            redisUtil.hset(token,"user", userJson);
            //  设置key的时间
            redisUtil.expire(token,60*60*30);
            // 响应客户端
            return VideoResponse.ok(token,userBase);
        }
        return  VideoResponse.error();
    }

    @Override
    public VideoResponse exit(String token) {
        // 从redis中删除对应的token
        redisUtil.del(token);
        return VideoResponse.ok();
    }

    @Override
    public VideoResponse checkLogin(String token) {
        if(token==null){
            return VideoResponse.error();
        }
        if(redisUtil.exists(token)){
            String userJson = redisUtil.hget(token, "user");
            // 将json转换为user对象
            UserBase userBase = JsonTools.json2object(userJson,UserBase.class);
            //  设置key的时间
            redisUtil.expire(token,60*60*30);
            return VideoResponse.ok(token,userBase);
        }
        return VideoResponse.error();
    }
}
